<template>
  <!-- 小区公告 -->
  <div class="houseAnn">
    <div data-v-539452e0 aria-label="Breadcrumb" role="navigation" class="el-breadcrumb">
      <span data-v-539452e0 class="el-breadcrumb__item">
        <span role="link" class="el-breadcrumb__inner is-link">小区管理</span>
        <span role="presentation" class="el-breadcrumb__separator">/</span>
      </span>
      <span data-v-539452e0 class="el-breadcrumb__item" aria-current="page">
        <span
          role="link"
          :class="{ 'is-link': form.isShow }"
          class="el-breadcrumb__inner"
          @click="backList"
        >小区公告</span>
        <span role="presentation" class="el-breadcrumb__separator">/</span>
      </span>
      <span data-v-539452e0 v-if="form.isShow" class="el-breadcrumb__item" aria-current="page">
        <span role="link" class="el-breadcrumb__inner">新增公告</span>
        <span role="presentation" class="el-breadcrumb__separator">/</span>
      </span>
      <!---->
    </div>

    <section class="section-content" v-loading="section.loading">
      <el-main class="content-wrapper">
        <el-row class="my-margin-top-20" :gutter="6" v-if="!form.isShow">
          <el-col :span="2" style="min-width:120px;">
            <el-button type="primary" size="small" @click="addAnn">新增公告</el-button>
          </el-col>
          <el-col :span="4">
            <el-input
              size="small"
              placeholder="请输入关键字"
              suffix-icon="el-icon-search"
              :clearable="true"
              @clear="cleanKey"
              v-model="table.queryKey"
              @keyup.enter.native="queryKey"
            ></el-input>
          </el-col>
          <el-col style="margin-left:10px;" :span="4" v-show="!form.isShow">
            <el-select
              @change="selectChange"
              size="small"
              clearable
              v-model="table.state"
              placeholder="请选择状态"
            >
              <el-option label="未发布" value="0"></el-option>
              <el-option label="已发布" value="1"></el-option>
            </el-select>
          </el-col>
        </el-row>
        <!-- table -->
        <el-row class="my-margin-top-10" v-show="!form.isShow">
          <el-table
            v-loading="table.loading"
            :data="table.tableData"
            border
            stripe
            style="width:100%"
            size="small"
            :highlight-current-row="true"
            ref="multipleTable"
          >
            <el-table-column label="标题" prop="title"></el-table-column>
            <el-table-column label="状态" width="90">
              <template slot-scope="scope">
                <span v-if="scope.row.state==1">已发布</span>
                <span v-if="scope.row.state==0">未发布</span>
              </template>
            </el-table-column>
            <el-table-column label="发布时间" prop="publishTime" width="130"></el-table-column>
            <el-table-column label="发布人" prop="publishUserName" width="220"></el-table-column>
            <el-table-column label="浏览数" prop="pageViews" width="60"></el-table-column>
            <el-table-column label="操作" width="300">
              <template slot-scope="scope">
                <el-button type="text" v-if="scope.row.state==0" @click="modify(scope.row)">编辑</el-button>
                <el-button type="text" @click="preview(scope.row)">预览</el-button>
                <el-button type="text" v-if="scope.row.state==0" @click="del(scope.row)">删除</el-button>
                <el-button v-if="scope.row.state==0" type="text" @click="issue(scope.row)">发布</el-button>
                <el-button
                  v-if="scope.row.state==1"
                  type="text"
                  @click="cancelIssue(scope.row)"
                >取消发布</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            class="my-margin-top-10 my-el-pagination"
            @current-change="currentChangeHandle"
            :current-page="table.currentPage"
            :page-size="table.pageSize"
            layout="total, prev, pager, next, jumper"
            :total="table.rowCount"
          ></el-pagination>
        </el-row>
        <!-- editor -->
        <el-row v-if="form.isShow" class="edit-row">
          <div class="writediarytitle" v-loading="ruleForm.loading">
            <el-form
              :model="ruleForm"
              :rules="rules"
              ref="ruleForm"
              label-width="60px"
              class="demo-ruleForm"
            >
              <el-form-item label="标题" prop="title">
                <el-input size="mini" v-model="ruleForm.title"></el-input>
              </el-form-item>
              <el-form-item class="el-form-item_data" label="内容" prop="region">
                <editor
                  :value="ruleForm.region"
                  style="height:515px;background:#fff"
                  @input="input"
                  @onEditorBlur="onEditorBlur"
                ></editor>
              </el-form-item>
              <el-form-item class="el-form-item_btn">
                <el-button type="primary" @click="submitForm('ruleForm')" size="small">保存</el-button>
                <el-button plain @click="resetForm('ruleForm')" size="small">返回</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-row>
      </el-main>
    </section>

    <el-dialog :visible.sync="edit.editDia" class="edit-dia-wrapper">
      <div class="ql-container ql-snow">
        <div class="ql-editor">
          <h2 class="editor-title">{{edit.content.title}}</h2>
          <p class="editor-sub-title">
            <span>{{edit.content.publishUserName}}</span>
            {{edit.content.publishTime}}
          </p>
          <div v-html="edit.content.content">{{edit.content.content}}</div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { setItem, getItem } from "../../tools/common";
import Editor from "./Editor.vue";
export default {
  data() {
    var titleVerification = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入标题"));
      } else {
        value = value.replace(/\s+/g, "");
        if (value === "") {
          callback(new Error("标题不能为空"));
        }
        callback();
      }
    };
    var ContentVerification = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入内容"));
      } else {
        console.log(value);
        value = value.replace(/\s+/g, "");
        console.log(value);
        if (value == "<p></p>") {
          callback(new Error("内容不能为空"));
        }
        callback();
      }
    };
    return {
      form: {
        isShow: false
      },
      table: {
        tableData: [],
        currentPage: 1,
        pageSize: 10,
        rowCount: 0,
        queryKey: "",
        state: null,
        loading: false
      },
      ruleForm: {
        title: "",
        region: "",
        // "add" 新增   "edit" 编辑
        state: "",
        noticeId: null,
        loading: false
      },
      rules: {
        title: [
          { validator: titleVerification, trigger: "blur" },
          { min: 1, max: 25, message: "长度在 1 到 25个字符", trigger: "blur" }
        ],
        region: [{ validator: ContentVerification, trigger: "blur" }]
      },
      edit: {
        editDia: false,
        content: {}
      },
      section: { loading: false }
    };
  },
  methods: {
    cleanKey() {
      this.table.currentPage = 1;
      this.table.queryKey = "";
      this.fetchData();
    },
    queryKey() {
      this.table.currentPage = 1;
      this.fetchData();
    },

    goBack() {
      this.form.isShow = false;
    },
    currentChangeHandle(currentPage) {
      this.table.currentPage = currentPage;
      this.fetchData();
    },
    input(value) {
      //富文本编辑器
      this.ruleForm.region = value;
      console.log(`this.ruleForm.region=${this.ruleForm.region}`);
    },
    onEditorBlur(value) {
      console.log(value);
    },

    fetchData() {
      let url = "/notice/list";
      let info = getItem("info") ? getItem("info") : {};
      let p = {
        communityId: info.communityId,
        start: (this.table.currentPage - 1) * this.table.pageSize,
        num: this.table.pageSize,
        title: this.table.queryKey
      };
      if (this.table.state == "1") {
        p.state = 1;
      } else if (this.table.state == "0") {
        p.state = 0;
      }
      this.table.laoding = true;
      this.$http
        .fetch(url, p)
        .then(res => {
          console.log(`res`, res);
          this.table.tableData = res.data.rows;
          this.table.rowCount = res.data.total;
          this.table.laoding = false;
        })
        .catch(err => {
          console.log("error");
          this.table.laoding = false;
        });
    },
    selectChange() {
      this.table.currentPage = 1;
      this.fetchData();
    },
    issue(_scope) {
      this.$confirm("是否确认发布", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          console.log(`发布`, _scope);
          let url = "/notice/publish";
          let p = {
            noticeId: _scope.noticeId
          };
          this.$http
            .fetch(url, p)
            .then(res => {
              this.$message({
                message: "发布成功",
                type: "success"
              });
              this.fetchData();
            })
            .catch(err => {});
        })
        .catch(() => {});
    },
    cancelIssue(_scope) {


      this.$confirm("是否确认取消发布", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
      console.log(`取消`, _scope);
      let url = "/notice/unpublish";
      let p = {
        noticeId: _scope.noticeId
      };
      this.$http
        .fetch(url, p)
        .then(res => {
          this.$message({
            message: "取消成功",
            type: "success"
          });
          this.fetchData();
        })
        .catch(err => {});

        })
        .catch(() => {});
    },
    addAnn() {
      this.form.isShow = true;
      this.ruleForm.title = "";
      this.ruleForm.region = "";
      this.ruleForm.state = "add";
      this.ruleForm.noticeId = null;
      console.log(this.ruleForm);
    },
    modify(_scope) {
      console.log(`编辑`, _scope);
      this.ruleForm.state = "edit";
      this.fetItemDetail(_scope.noticeId);
    },
    preview(_scope) {
      console.log(`预览`, _scope);
      let url = "/notice/detail";
      let p = { noticeId: _scope.noticeId };
      this.section.loading = true;
      this.$http
        .fetch(url, p)
        .then(res => {
          console.log(`res`, res);
          this.edit.editDia = true;
          this.edit.content = res.data;
          this.section.loading = false;
        })
        .catch(err => {
          this.section.loading = false;
        });
    },
    del(_scope) {
      this.$confirm("确定删除公告？", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let url = "/notice/delete";
          let p = {
            noticeId: _scope.noticeId
          };
          this.$http
            .fetch(url, p)
            .then(res => {
              this.$message({
                message: "删除成功",
                type: "success"
              });
              this.fetchData();
            })
            .catch(err => {});
        })
        .catch(() => {});
    },
    resetForm(formName) {
      //退出编辑或写日志
      this.ruleForm.title = "";
      this.ruleForm.region = "";
      this.form.isShow = false;
    },
    submitForm(formName) {
      //提交进行表单验证 通过state判断是写日志还是编辑日志
      this.$refs[formName].validate(valid => {
        console.log(`valid`, valid);
        if (valid) {
          this.annAjax(this.ruleForm.state);
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // edit传后台
    annAjax(_state) {
      let url = "";
      let p = {};
      let info = getItem("info");
      p.title = this.ruleForm.title;
      p.content = this.ruleForm.region;
      console.log(`p.content`, p.content);
      if (_state == "add") {
        url = "/notice/add";
        p.communityId = info.communityId;
      } else {
        url = "/notice/modify";
        p.noticeId = this.ruleForm.noticeId;
      }
      this.ruleForm.loading = true;
      this.$http
        .fetch(url, p)
        .then(res => {
          console.log(`res`, res);
          let msg = "";
          if (_state == "add") {
            msg = "新增成功";
          } else {
            msg = "编辑成功";
          }
          this.$message({
            message: msg,
            type: "success"
          });
          console.log("....");
          this.form.isShow = false;
          this.fetchData();
          this.ruleForm.loading = false;
        })
        .catch(err => {
          this.ruleForm.loading = false;
        });
    },
    fetItemDetail(noticeId) {
      let url = "/notice/detail";
      let p = { noticeId: noticeId };
      this.$http
        .fetch(url, p)
        .then(res => {
          console.log(`res`, res);
          this.ruleForm.title = res.data.title;
          console.log(`res.data.content`, res.data.content);
          this.ruleForm.region = res.data.content;
          this.form.isShow = true;
          this.ruleForm.noticeId = noticeId;
        })
        .catch(err => {});
    },
    backList() {
      if (this.form.isShow) {
        this.form.isShow = false;
      }
    }
  },
  components: {
    editor: Editor
  },
  mounted() {
    this.fetchData();
  }
};
</script>

<style scoped>
.edit-row {
  margin-top: 20px;
}
.edit-dia-wrapper >>> .el-dialog {
  min-width: 980px;
}
.edit-dia-wrapper .ql-container.ql-snow {
  border: none;
}
.editor-title {
  text-align: center;
}
.editor-sub-title {
  text-align: right;
  margin-right: 40px;
}
.editor-sub-title span {
  margin-right: 10px;
}
/* .span-sec >>> .el-breadcrumb__inner:hover {
    color: #409EFF;
    cursor: pointer;
} */
</style>


